﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using WCBG.ToolsForUnity.Tools;

public class DMKL_PKGamePlay : ReceiverBaseMono, IEasyLoading, IEasyEffect
{

    private readonly string audioBasePath = "story_danmai/story_danmai_audio/";
    private readonly string audioStart = "402030522";   // XX，我们挡住霸王龙号吧。
    private readonly string audioGood = "402010110";        // 你真棒
    private readonly string audioComplete = "402030526";    // 耶！我们赢了！
    private readonly string audioLevel1 = "402030523";    // 跟我一起喊——勇往直前！
    private readonly string audioLevel2 = "402030524";    // 跟我一起喊——锐不可当！
    private readonly string audioLevel3 = "402030525";    // 跟我一起喊——势如破竹！

    private readonly string audioJiqirenLose = "602030407";    // 机器人被撞到了
    private readonly string audioKonglongLose = "602030408";    // 恐龙被撞到了
    private readonly string audioKonglongO = "602030409";    // 最后一次被击倒的悲伤叫喊

    private readonly string scenePath = "story_danmaikonglong/story_danmai_prefab/302030400";    // 场景路径
    private const string FIGHT_EFFECT_PATH = "Effect/502002036";
    private const string LOSE_EFFECT_PATH = "Effect/502002037";

    public string nextTimelineID;
    public string[] hideObjNameArray;

    public Transform m_ledi;
    public Transform m_jiqiren;
    public Transform m_konglong;
    public Transform m_jiqiren_fightpoint;
    public Transform m_konglong_fightpoint;
    public Transform clickEffect;
    public Transform fightEffectPos;

    private Animator m_jiqirenAnimator;
    private Animator m_konglongAnimator;

    private Vector3 m_jiqirenStartPoint;
    private Vector3 m_konglongStartPoint;

    private int lediLoseCount;
    private int lediWinCount;

    private float m_lediProgress;
    private float m_konglongProgress;

    private Camera m_camera;

    private GameObject m_scene;


    void Start()
    {
        lediLoseCount = 0;
        m_lediProgress = m_konglongProgress = 1;
        m_jiqirenStartPoint = m_jiqiren.position;
        m_konglongStartPoint = m_konglong.position;

        m_jiqiren_fightpoint.gameObject.SetActive(false);
        m_konglong_fightpoint.gameObject.SetActive(false);
        clickEffect.gameObject.SetActive(false);

        m_jiqirenAnimator = m_jiqiren.GetComponentInChildren<Animator>();
        m_konglongAnimator = m_konglong.GetComponentInChildren<Animator>();
        m_camera = GetComponentInChildren<Camera>();

        m_ledi.GetChild(0).GetComponent<Animator>().CrossFade("sit_p", 0.01f);
        m_konglongAnimator.CrossFade("idell", 0.1f);

        //CreateScene();

        FEasyInput.AddEvent(EEasyInputType.OnDown, FEasyInput_OnDown);

        gameObject.SetActive(false);
    }
    //void Update()
    //{
    //    if (Input.GetKeyDown(KeyCode.Space))
    //    {
    //        StartCoroutine(Fight(IsLediWin()));
    //    }
    //}

    protected override void OnGameStart()
    {
        base.OnGameStart();

        this.StartLoadingAndEndEx(() =>
        {
            //FTimelineDispatch.DestroyTimeline(TimelineID);
            StartGame();
        });
    }

    private void StartGame()
    {
        gameObject.SetActive(true);
        HideSceneObj();
        WindowManager.Instance.OpenWindow(WinNames.StoryDMKLPKPanel);
        PlayAudio(audioStart, () =>
        {
            StartLevel();
        });


        GameObject go1 = FTimelineDispatch.GetTimelineObj(TimelineID);
        if (go1 != null)
        {
            Transform target = go1.transform.Find("30005_ShadowProjecter");
            if (target != null)
            {
                target.GetComponent<DynamicShadowProjector.DrawTargetObject>().RefreshShaowProjecter();
            }
        }
    }

    private void FEasyInput_OnDown()
    {

        Transform target = FTools.GetRaycastHitTarget(m_camera, Input.mousePosition, 99999);
        if (target != null && target == clickEffect)
        {
            clickEffect.gameObject.SetActive(false);
            StartFight();
        }
    }

    private void StartLevel()
    {
        if (lediWinCount < 3)
            clickEffect.gameObject.SetActive(true);
        else
        {
            PlayAudio(audioComplete, () => {
                Debug.Log("----------------  游戏完成!");

                this.StartLoadingAndEndEx(() =>
                {
                    FTimelineDispatch.PlayTimeline(nextTimelineID);
                }, () =>
                {
                    WindowManager.Instance.CloseWindow(WinNames.StoryDMKLPKPanel);
                    FTimelineDispatch.DestroyTimeline(TimelineID);
                });
            });
        }
    }

    private void StartFight()
    {
        string[] audioArray = new string[3] { audioLevel1, audioLevel2, audioLevel3 };
        PlayAudio(audioArray[lediWinCount], () => {

            WindowManager.Instance.OpenWindow(WinNames.StoryMicroPanel);
            StoryMicroWindow.Instance.AddEvent((result) =>
            {
                WindowManager.Instance.CloseWindow(WinNames.StoryMicroPanel);
                StartCoroutine(Fight(IsLediWin()));
            });
        });
    }

    IEnumerator Fight(bool isLediWin)
    {
        m_jiqirenAnimator.CrossFade("run", 0.1f);
        m_konglongAnimator.CrossFade("run", 0.1f);

        yield return new WaitForSeconds(0.2f);

        float duration = 0.5f;
        m_jiqiren.DOMove(m_jiqiren_fightpoint.position, duration).SetEase(Ease.Linear);
        m_konglong.DOMove(m_konglong_fightpoint.position, duration).SetEase(Ease.Linear);

        yield return new WaitForSeconds(duration);
        
        m_jiqirenAnimator.CrossFade("fight", 0.1f);
        m_konglongAnimator.CrossFade("fight", 0.1f);

        this.PlayEffectEx(FIGHT_EFFECT_PATH, fightEffectPos, 5);

        yield return new WaitForSeconds(0.3f);

        UpdateProgress(isLediWin);

        if (isLediWin)
        {
            lediWinCount++;

            m_jiqirenAnimator.CrossFade("idell", 0.1f);
            m_konglongAnimator.CrossFade("crash", 0.1f);
            m_konglong.DOMove(m_konglongStartPoint, 0.5f).SetEase(Ease.Linear).OnComplete(()=> {
                this.PlayEffectEx(LOSE_EFFECT_PATH, m_konglongStartPoint, 5);
            });
            


            if (lediWinCount < 3)
            {
                PlayAudio(audioKonglongLose);

                yield return new WaitForSeconds(1.5f);
                m_konglongAnimator.CrossFade("stand_up", 0.1f);
                yield return new WaitForSeconds(1.5f);
                m_konglongAnimator.CrossFade("idell", 0.1f);
                m_jiqiren.DOMove(m_jiqirenStartPoint, duration).SetEase(Ease.Linear);
            }
            else
            {
                PlayAudio(audioKonglongO);
            }

            //if (lediWinCount < 3)
            //{
            //    m_konglongAnimator.CrossFade("idell", 0.1f);
            //    m_jiqiren.DOMove(m_jiqirenStartPoint, duration).SetEase(Ease.Linear);
            //}
        }
        else
        {
            lediLoseCount++;

            m_jiqirenAnimator.CrossFade("fall", 0.1f);
            m_konglongAnimator.CrossFade("idell", 0.1f);
            m_jiqiren.DOMove(m_jiqirenStartPoint, 0.2f).SetEase(Ease.Linear).OnComplete(() =>
            {
                this.PlayEffectEx(LOSE_EFFECT_PATH, m_jiqirenStartPoint, 5);
            });

            PlayAudio(audioJiqirenLose);

            yield return new WaitForSeconds(1.5f);
            m_jiqirenAnimator.CrossFade("up", 0.1f);

            yield return new WaitForSeconds(1.5f);

            //m_jiqirenAnimator.CrossFade("idell", 0.1f);
            m_konglong.DOMove(m_konglongStartPoint, duration).SetEase(Ease.Linear);
        }

        yield return new WaitForSeconds(1.5f);

        StartLevel();

    }

    private void UpdateProgress(bool isLediWin)
    {
        if (isLediWin)
        {
            m_konglongProgress -= 1 / 3f;
            if (m_konglongProgress < 0)
                m_konglongProgress = 0;

            StoryDMKLPKWindow.Instance.UpdateKonglongBar(m_konglongProgress);
        }
        else
        {
            m_lediProgress -= 1 / 3f;
            if (m_lediProgress < 0)
                m_lediProgress = 0;

            StoryDMKLPKWindow.Instance.UpdateLediBar(m_lediProgress);
        }
    }

    private bool IsLediWin()
    {
        if (lediLoseCount > 1)
            return true;
        bool result = Random.Range(0, 3) > 0;
        return result;
    }

    private void PlayAudio(string name, System.Action callback = null)
    {
        GameAudioSource audio = this.PlayAudioEx(audioBasePath + name);
        this.AddTimerEx(audio.Length, callback);
    }

    private void CreateScene()
    {
        m_scene = Res.LoadObj(scenePath);
        if (m_scene != null)
        {
            m_scene.transform.SetParent(transform);
        }
    }

    private void HideSceneObj()
    {
        GameObject go = FTimelineDispatch.GetTimelineObj(TimelineID);
        if (go != null && hideObjNameArray != null)
        {
            Transform target = go.transform;
            
            foreach (string name in hideObjNameArray)
            {
                Transform t = target.Find(name);
                if (t != null) t.SetActive(false);

            }
        }
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        FEasyInput.RemoveEvent(EEasyInputType.OnDown, FEasyInput_OnDown);
        WindowManager.Instance.CloseWindow(WinNames.StoryMicroPanel);
        WindowManager.Instance.CloseWindow(WinNames.StoryDMKLPKPanel);
    }



}
